import { createRouter, createWebHistory } from "vue-router";
import store from "@/store/index";

const VueRouter = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      meta: { requiredLogin: true },
      component: () => import("@/views/Home.vue"),
    },
    {
      path: "/login",
      name: "login",
      meta: { redirectAlreadyLogin: true },
      component: () => import("@/views/Login.vue"),
    },
  ],
});

VueRouter.beforeEach((to, from, next) => {
  const { requiredLogin, redirectAlreadyLogin } = to.meta;

  if (store.state.isLogin) {
    if (redirectAlreadyLogin) {
      if (to.path === from.path) {
        next();
      } else {
        next({
          path: from.fullPath,
          replace: true,
        });
      }
    } else {
      next();
    }
  } else {
    if (requiredLogin) {
      next("login");
    } else {
      next();
    }
  }
});

export default VueRouter;
